/*
 * common.c
 *
 *  Created on: Dec 25, 2023
 *      Author: jetpo
 */

#include "common.h"

int str2int(uint8_t *p_str, uint32_t *pout_intmum)
{
    uint32_t i = 0, res = 0;
    uint32_t val = 0;

    if ((p_str[0] == '0') && ((p_str[1] == 'x') || (p_str[1] == 'X')))
    {
        i = 2;
        while ((i < 11) && (p_str[i] != '\0'))
        {
            if (ISVALIDHEX(p_str[i]))
            {
                val = (val << 4) + CONVERTHEX(p_str[i]);
            }
            else
            {
                /* Return 0, Invalid input */
                res = 0;
                break;
            }
            i++;
        }

        /* valid result */
        if (p_str[i] == '\0')
        {
            *pout_intmum = val;
            res = 1;
        }
    }
    else /* max 10-digit decimal input */
    {
        while ((i < 11) && (res != 1))
        {
            if (p_str[i] == '\0')
            {
                *pout_intmum = val;
                /* return 1 */
                res = 1;
            }
            else if (((p_str[i] == 'k') || (p_str[i] == 'K')) && (i > 0))
            {
                val = val << 10;
                *pout_intmum = val;
                res = 1;
            }
            else if (((p_str[i] == 'm') || (p_str[i] == 'M')) && (i > 0))
            {
                val = val << 20;
                *pout_intmum = val;
                res = 1;
            }
            else if (ISVALIDDEC(p_str[i]))
            {
                val = val * 10 + CONVERTDEC(p_str[i]);
            }
            else
            {
                /* return 0, Invalid input */
                res = 0;
                break;
            }
            i++;
        }
    }

    return res;
}
